<template>
  <div id="applied-list">
    <div class="title mb-10">
      <Divider style="margin-top: 10px;">
        <h3 style="color: #17233d;">
          {{ title }}
        </h3>
      </Divider>
    </div>
    <div class="top-toolbar pr-10 pl-10">
      <Row type="flex" v-if="userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 || userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || userAccess.indexOf('ROLE_ROOT') > -1">
        <Col :xs="24" :sm="24" :md="11" :lg="7" class="mb-15">
          <span>学院：</span>
          <div style="display: inline-block;width: calc(100% - 42px);">
            <Select v-if="userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || userAccess.indexOf('ROLE_ROOT') > -1" :size="selectSize" v-model="filter.institute" :enabledPreventOverflow="enabledPreventOverflow" placeholder="请选择学院进行检索" filterable @on-change="onChangeInstitute">
              <Option v-for="(item, index) in institutes" :value="item" :key="index">{{ item }}</Option>
            </Select>
            <Input v-else v-model="filter.institute" readonly placeholder="当前学院" />
          </div>
        </Col>
        <Col :xs="24" :sm="24" :md="{span: 11, offset: 2}" :lg="{span: 6, offset: 1}" class="mb-15">
          <span>教师：</span>
          <Select style="width: calc(100% - 42px);"
                  :size="selectSize"
                  v-model="filter.teacherCode"
                  :enabledPreventOverflow="enabledPreventOverflow"
                  :placeholder="filter.institute ? '请选择教师进行检索' : '请先选择学院'"
                  filterable
                  @on-change="onChangeTeacher" :disabled="!filter.institute">
            <Option v-if="teachers.length > 0" value="all" key="all">全部</Option>
            <Option v-for="(item, index) in teachers" :value="item.code" :key="index">{{ item.name }}</Option>
          </Select>
        </Col>
        <Col :xs="24" :sm="24" :md="11" :lg="{span: 9, offset: 1}" class="mb-15">
          <Input v-model="search.keyword"
                 search
                 clearable
                 :disabled="!search.criteria"
                 :placeholder="inputPlaceholder"
                 @on-search="onSearch"
                 @on-change="onInputChange">
            <Select slot="prepend"
                    style="width: 100px;"
                    :size="selectSize"
                    v-model="search.criteria"
                    :enabledPreventOverflow="enabledPreventOverflow"
                    placeholder="搜索条件"
                    filterable
                    clearable
                    @on-change="onChangeSearchCriteria">
              <Option value="courseName" key="courseName">课程名称</Option>
              <Option value="teacherName" key="teacherName">教师名称</Option>
            </Select>
          </Input>
        </Col>
      </Row>
      <Row type="flex">
        <Col :xs="24" :sm="11" :md="11" :lg="7" class="mb-15">
          <span>类别：</span>
          <div style="display: inline-block;width: calc(100% - 42px);">
            <Select :size="selectSize"
                    v-model="filter.type"
                    :enabledPreventOverflow="enabledPreventOverflow"
                    placeholder="请选择类别进行检索"
                    @on-change="onChangeType"
                    filterable>
              <Option value="all" key="all">全部</Option>
              <Option value="COURSE" key="COURSE">普通课程</Option>
              <Option value="TRAINING" key="TRAINING">实训</Option>
            </Select>
          </div>
        </Col>
        <Col :xs="24" :sm="{span: 12, offset: 1}" :md="{span: 11, offset: 2}" :lg="{span: 6, offset: 1}" class="mb-15">
          <span>学期：</span>
          <Select style="width: calc(100% - 42px);"
                  :size="selectSize"
                  v-model="semesterString"
                  :enabledPreventOverflow="enabledPreventOverflow"
                  placeholder="请选择学期进行检索"
                  filterable
                  @on-change="onChangeSemester">
            <Option v-for="(item, index) in semesters" :value="item" :key="index">{{ item.split('/', 2)[0] }} ~ {{ Number(item.split('/', 2)[0]) + 1 }}学年第{{ ['一', '二'][item.split('/', 2)[1]] }}学期</Option>
          </Select>
        </Col>
        <Col :xs="24" :sm="24" :md="11" :lg="{span: 9, offset: 1}" class="mb-15">
          <span>课程类别：</span>
          <Select style="width: calc(100% - 70px);"
                  :size="selectSize"
                  v-model="filter.courseType"
                  :enabledPreventOverflow="enabledPreventOverflow"
                  :disabled="filter.type === 'TRAINING'"
                  :not-found-text="loading.courseType ? '加载课程类别中，请稍等...' : '暂无课程类别'"
                  placeholder="请选择课程类别进行检索"
                  filterable
                  multiple>
            <!-- <Option value="all" key="all">全部</Option> -->
            <Option v-for="(item, index) in options.courseType" :value="item.value" :key="index">{{ item.label }}</Option>
          </Select>
        </Col>
      </Row>
      <Row type="flex" v-if="!hideOperationBtn">
        <Col :xs="24" :sm="24" :md="24" :lg="24">
          <Button type="success" @click="addApplyForm" class="mb-15">
            <font-awesome-icon icon="plus-circle"/>
            添加普通实验申请表
          </Button>
          <Divider type="vertical" class="mb-15"/>
          <Button type="info" @click="addApplyTraining" class="mb-15">
            <font-awesome-icon icon="plus-circle"/>
            添加实训申请表
          </Button>
          <Divider type="vertical" class="mb-15" />
          <Button type="error" @click="batchDelete" class="mb-15" :disabled="table.selection.length === 0">
            <font-awesome-icon icon="times-circle"/>
            批量删除
          </Button>
        </Col>
      </Row>
    </div>
    <div class="table-container small-table">
      <Table :border="table.showBorder"
             :stripe="table.showStripe"
             :show-header="table.showHeader"
             :size="table.size"
             :data="table.data"
             :columns="table.columns"
             :loading="table.loading"
             :disabledHover="table.disabledHover"
             :highlight-row="table.highlightRow"
             :row-class-name="tableRowClassName"
             @on-expand="onExpand"
             @on-row-click="onRowClick"
             @on-sort-change="onSortChange"
             @on-selection-change="onSelectionChange">
        <template slot-scope="{ row, index }" slot="action">
          <div style="margin-top: 5px; margin-bottom: 5px;">
            <Button v-if="!showSelectBtn" type="default" :size="btnSize" style="margin-bottom: 5px;" @click="addSingle(row)" class="add-single">
              <font-awesome-icon icon="plus-circle" style="margin-right: 3px;"/>
              新增单个实验
            </Button>
            <Button v-if="!showSelectBtn" type="info" :size="btnSize" style="margin-bottom: 5px;" @click="edit(row)">
              <font-awesome-icon icon="edit"/>
              修改课程信息
            </Button>
            <Button v-if="!showSelectBtn" type="success" :size="btnSize" style="margin-bottom: 5px;"
                    @click="exportToExcel(row)" :loading="loading.export[row._index]" @exported="exported(index)"
                    :disabled="loading.export.indexOf(true) > -1">
              <font-awesome-icon icon="file-excel" style="margin-right: 4px;" v-if="!loading.export[row._index]" />
              导出该申请表
            </Button>
            <Button v-if="!showSelectBtn" type="warning" :size="btnSize" @click="del(row)">
              <font-awesome-icon icon="trash-alt" style="margin-right: 3px;"/>
              删除该申请表
            </Button>
            <Button v-if="showSelectBtn" type="info" :size="btnSize" @click="select(row)">
              <font-awesome-icon icon="check-circle"/>
              选择
            </Button>
          </div>
        </template>
      </Table>
    </div>
    <div class="pagination text-right pr-15 mt-20">
      <Page :current="pageBuilder.pageNum"
            :size="page.size"
            :total="page.total"
            :page-size="page.pageSize"
            :page-size-opts="page.pageSizeOpts"
            :show-sizer="page.showSizer"
            :simple="page.simple"
            :show-elevator="page.showElevator"
            :show-total="page.showTotal"
            @on-change="onPageNumChange"
            @on-page-size-change="onPageSizeChange"/>
    </div>
    <div class="modal-container">
      <Modal v-model="deleteModal.show" :closable="deleteModal.closable" :mask-closable="deleteModal.maskClosable" width="360" class-name="vertical-center-modal">
        <p slot="header" style="color: #FF5722; text-align: center;">
          <font-awesome-icon icon="info-circle"/>
          删除确认
        </p>
        <div style="text-align: center;">
          <p>确认删除所选的实验室申请表吗？</p>
        </div>
        <div slot="footer">
          <Button type="error" size="large" long :loading="deleteModal.loading" @click="confirmDel">删除</Button>
        </div>
      </Modal>
      <Modal v-model="modal.edit.show" width="95" footer-hide @on-ok="modal.edit.show = false" @on-cancel="closeSaveModal" id="edit-modal" class="mb-50-modal">
        <p slot="header" class="text-center">{{ modal.edit.title }}</p>
        <div>
          <save-course-base
              v-if="modal.edit.show && modal.edit.expType === 'COURSE'"
              :app_code="modal.edit.appCode"
              v-on:failFillFrom="failFillBaseFrom"
              v-on:saveSuccess="saveBaseSuccess"
              ></save-course-base>
            <save-training-base
            v-if="modal.edit.show && modal.edit.expType === 'TRAINING'"
            :app_code="modal.edit.appCode"
            v-on:failFillFrom="failFillBaseFrom"
            v-on:saveSuccess="saveBaseSuccess"
              ></save-training-base>
        </div>
      </Modal>
      <Modal v-model="modal.saveSingle.show" width="95" footer-hide @on-ok="modal.saveSingle.show = false" @on-cancel="closeSaveModal" id="saveSingle-modal" class="mb-50-modal">
        <p slot="header" class="text-center">{{ modal.saveSingle.title }}</p>
        <div>
          <save-course-exp
            v-if="modal.saveSingle.show && modal.saveSingle.exp_type === 'COURSE'"
            :fieldsetTitle="modal.saveSingle.fieldsetTitle"
            :app_code="modal.saveSingle.app_code"
            :sid="modal.saveSingle.sid"
            :expIndex="modal.saveSingle.expIndex"
            :editSingle="modal.saveSingle.editSingle"
            v-on:failFillFrom="failFillExpFrom"
            v-on:saveSuccess="saveExpSuccess"
          ></save-course-exp>
          <save-training-exp
            v-if="modal.saveSingle.show && modal.saveSingle.exp_type === 'TRAINING'"
            :fieldsetTitle="modal.saveSingle.fieldsetTitle"
            :app_code="modal.saveSingle.app_code"
            :sid="modal.saveSingle.sid"
            :expIndex="modal.saveSingle.expIndex"
            :editSingle="modal.saveSingle.editSingle"
            v-on:failFillFrom="failFillExpFrom"
            v-on:saveSuccess="saveExpSuccess"
          ></save-training-exp>
        </div>
      </Modal>
      <Modal v-model="modal.detail.show" footer-hide width="90%" class="d-none mb-50-modal">
        <p slot="header" class="text-center" style="color: #276f86;">{{ modal.detail.title }}</p>
        <applied-form-detail-table ref="appliedFormDetailTable" v-if="modal.detail.show" :code="modal.detail.code" :index="modal.detail.index" :title="modal.detail.title" :immediate="true" @exported="exported"/>
      </Modal>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import AppliedListExpend from './applied-list-expend.vue'
import AppliedFormDetailTable from '_c/applied-form-detail-table/applied-form-detail-table'
import EditAppliedForm from '_v/lab-apply/edit-applied-form/edit-applied-form'
import SaveCourseBase from '_c/save-course-base/save-course-base'
import SaveCourseExp from '_c/save-course-exp/save-course-exp'
import SaveTrainingBase from '_c/save-training-base/save-training-base'
import SaveTrainingExp from '_c/save-training-exp/save-training-exp'
import {
  getInstituteList,
  getTeacherList,
  getAppliedFormList,
  getAppliedFormDetail,
  getCourseType,
  modifyAppFormStatus
} from '@/api/applied-form-mgmt'
import {
  getFirstWeekDateList,
  getCurrTermDateInfo
} from '@/api/lab-applied-summary-sheet'
import { activeTableMove } from '@/libs/tools'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faEdit, faPlusCircle, faTrashAlt, faTimesCircle, faCheckCircle, faInfoCircle, faFileExcel } from '@fortawesome/free-solid-svg-icons'
library.add(faEdit)
library.add(faTrashAlt)
library.add(faPlusCircle)
library.add(faTimesCircle)
library.add(faCheckCircle)
library.add(faInfoCircle)
library.add(faFileExcel)
export default {
  components: {
    AppliedListExpend,
    'applied-form-detail-table': AppliedFormDetailTable,
    'edit-applied-form': EditAppliedForm,
    'save-course-base': SaveCourseBase,
    'save-course-exp': SaveCourseExp,
    'save-training-base': SaveTrainingBase,
    'save-training-exp': SaveTrainingExp
  },
  props: {
    // 显示“选择”按钮
    showSelectBtn: {
      type: Boolean,
      default: false
    },
    // 隐藏表格的checkbox列
    hideCheckBox: {
      type: Boolean,
      default: false
    },
    // 隐藏表格上方的操作按钮
    hideOperationBtn: {
      type: Boolean,
      default: false
    },
    // 申请表的类型
    formType: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      firstEnter: false,
      title: '实验室申请表列表',
      btnSize: 'small',
      selectSize: 'default',
      enabledPreventOverflow: false,
      semesters: [],
      semesterString: '',
      filter: {
        institute: '',
        teacherCode: '',
        type: 'all',
        studyYear: '',
        semester: '',
        teacherName: '',
        courseName: '',
        courseType: []
      },
      search: {
        criteria: '',
        keyword: ''
      },
      options: {
        courseType: []
      },
      loading: {
        courseType: true,
        export: []
      },
      userAccess: [],
      institutes: [],
      teachers: [],
      table: {
        showBorder: true,
        showStripe: false,
        showHeader: true,
        fixedHeader: true,
        height: '',
        disabledHover: false,
        loading: false,
        size: 'small',
        selection: [],
        currRowIndex: '',
        columns: [{
          type: 'expand',
          width: 50,
          title: '展开',
          align: 'center',
          render: (h, params) => {
            return h(AppliedListExpend, {
              props: {
                row: [params.row.formData],
                code: params.row.appCode,
                showActionColumn: true,
                showSelectionColumn: true,
                prefixClass: '.ivu-table-tbody tr.row' + params.row._index + ' + tr'
              },
              on: {
                refresh: this.refreshTable
              }
            })
          }
        }, {
          type: 'selection',
          width: 40,
          align: 'center'
        }, {
          type: 'index',
          title: '序号',
          width: 50,
          align: 'center'
        }, {
          title: '类别',
          width: 55,
          key: 'type',
          align: 'center',
          // filters: [{
          //   label: '普通课程',
          //   value: 'COURSE'
          // }, {
          //   label: '实训',
          //   value: 'TRAINING'
          // }],
          // filterMultiple: false,
          // filterRemote: function (value) {
          //   this.filter.type = value.length <= 0 ? '' : value[0]
          //   // 动态设置筛选列的filteredValue，防止iview表格点击列排序时把filters清空（显示上）
          //   if (this.filter.type) {
          //     this.getTableColumnByKey('type')[0].filteredValue = [this.filter.type]
          //     if (this.filter.type === 'TRAINING') {
          //       this.filter.courseType.length = 0
          //       this.$delete(this.getTableColumnByKey('courseType')[0], 'filteredValue')
          //     }
          //   } else {
          //     this.filter.courseType.length = 0
          //     this.$delete(this.getTableColumnByKey('courseType')[0], 'filteredValue')
          //     delete this.getTableColumnByKey('type')[0].filteredValue
          //   }
          // },
          render: (h, params) => {
            const row = params.row
            const color = row.exp_type === 'TRAINING' ? 'cyan' : 'blue'
            const text = row.exp_type === 'TRAINING' ? '实训' : '普通'
            return h('Tag', {
              props: {
                color: color
              },
              style: {
                marginRight: '0'
              }
            }, text)
          }
        }, {
          title: '教师',
          key: 'teacherName',
          width: 70,
          align: 'center'
        }, {
          title: '学年',
          key: 'studyYear',
          width: 45,
          // sortType: 'normal',
          // sortable: 'custom',
          // sortMethod: (a, b, type) => {
          // },
          align: 'center',
          // render: (h, params) => {
          //   return h('span', params.row.studyYear + ' ~ ' + (Number(params.row.studyYear) + 1))
          // }
          render: (h, params) => {
            return h('span', [
              params.row.studyYear,
              h('br'),
              ' ~ ',
              h('br'),
              (Number(params.row.studyYear) + 1)
            ])
          }
        }, {
          title: '学期',
          key: 'semester',
          width: 45,
          align: 'center',
          // filters: [{
          //   label: '第一学期',
          //   value: 0
          // }, {
          //   label: '第二学期',
          //   value: 1
          // }],
          // filterMultiple: false,
          // filterRemote: function (value) {
          //   this.filter.semester = value.length <= 0 ? '' : value[0]
          //   // 动态设置筛选列的filteredValue，防止iview表格点击列排序时把filters清空（显示上）
          //   if (this.filter.semester !== '') {
          //     this.getTableColumnByKey('semester')[0].filteredValue = [this.filter.semester]
          //   } else {
          //     delete this.getTableColumnByKey('semester')[0].filteredValue
          //   }
          // },
          render: (h, params) => {
            return h('span', params.row.semester === 0 ? '一' : '二')
          }
        }, {
          title: '课程名称',
          key: 'courseName',
          minWidth: 110,
          align: 'center'
        }, {
          title: '课程类别',
          key: 'courseType',
          width: 65,
          align: 'center',
          // filters: undefined,
          // filterRemote: function (value) {
          //   this.filter.courseType = value.length <= 0 ? [] : value
          //   if (this.filter.courseType.length > 0) {
          //     this.filter.type = 'COURSE'
          //     this.getTableColumnByKey('courseType')[0].filteredValue = this.filter.courseType
          //     this.$set(this.table.columns.slice(-12, -11)[0], 'filteredValue', ['COURSE'])
          //   } else {
          //     delete this.getTableColumnByKey('courseType')[0].filteredValue
          //   }
          // },
          // filterMultiple: true,
          render: (h, params) => {
            return h('span', params.row.courseType || '无')
          }
        }, {
          title: '实验教材',
          key: 'textbook',
          minWidth: 160,
          align: 'center'
        }, {
          title: '实验项数',
          key: 'numberOfExperiment',
          width: 60,
          align: 'center'
        }, {
          title: '教学对象',
          minWidth: 200,
          className: 'custom-table-cell-style',
          align: 'center',
          render: (h, params) => {
            return h('div', params.row.classes.map((item, index) => {
              return h('div', [
                h('span', params.row.exp_type === 'TRAINING' ? (item ? item.grade + '级' + item.major : '') : (item ? item.grade + '级' + item.major + item.sclass + '班' : '')),
                h('br', {
                  style: {
                    display: (index === params.row.classes.length - 1) ? 'none' : ''
                  }
                })
              ])
            }))
          }
        }, {
          title: '人数',
          key: 'stuNum',
          width: 50,
          align: 'center'
        }, {
          title: '创建时间',
          key: 'createDate',
          minWidth: 80,
          align: 'center',
          sortType: 'normal',
          sortable: 'custom',
          sortMethod: (a, b, type) => {
          }
        }, {
          title: '操作',
          slot: 'action',
          width: this.showSelectBtn ? 90 : 130,
          align: 'center'
          // fixed: 'right'
        }],
        data: [],
        highlightRow: false,
        selectedRows: []
      },
      deleteModal: {
        loading: false,
        show: false,
        closable: true,
        maskClosable: true
      },
      page: {
        size: 'small',
        total: 0,
        pageSize: 5,
        showSizer: true,
        showElevator: true,
        showTotal: true,
        pageSizeOpts: [5, 10, 20, 30, 40, 50],
        simple: false
      },
      pageBuilder: {
        pageSize: 5,
        pageNum: 1,
        order: []
      },
      pageBuilderOrder: new Map(),
      /*
       * vue的响应式系统不支持Map和Set,
       * 当Map与Set里面的元素变化时，
       * Vue追踪不到这些变化，无法做出响应
       * 解决方法是用一个可序列化的变量来手动追踪变化
       */
      pageBuilderOrderChangeTracker: 1,
      modal: {
        edit: {
          show: false,
          title: '修改申请表',
          expType: 'COURSE',
          appCode: null
        },
        saveSingle: {
          show: false,
          exp_type: 'COURSE',
          fieldsetTitle: '',
          title: '新增实验项目',
          app_code: null,
          sid: null,
          expIndex: null,
          editSingle: true
        },
        detail: {
          show: false,
          code: '',
          index: '',
          title: ''
        }
      }
    }
  },
  computed: {
    inputPlaceholder () {
      if (!this.search.criteria) {
        return '请先选择搜索条件'
      } else {
        if (this.search.criteria === 'teacherName') {
          return '请输入教师姓名进行搜索...'
        } else if (this.search.criteria === 'courseName') {
          return '请输入课程名称进行搜索...'
        }
      }
    }
  },
  methods: {
    ...mapActions([
      'getUserInfo'
    ]),
    tableRowClassName (row, index) {
      return 'row' + index
    },
    async renderTable (filter, pageBuilder) {
      // 初始化表格
      this.table.loading = true
      this.loading.export = []
      try {
        let response = await getAppliedFormList(filter, pageBuilder)
        let res = response.data
        if (res.code === 1) {
          this.table.data = res.data.content
          this.page.total = res.data.totalElements
          this.loading.export = new Array(res.data.numberOfElements)
          this.loading.export.fill(false)
          this.$nextTick(() => {
            document.querySelectorAll('#applied-list .ivu-table-cell-expand').forEach(element => {
              element.innerHTML = `<button type="button" style="padding: 1px 7px 2px;" class="ivu-btn ivu-btn-dashed"><span>修改</span></button>`
            })
            this.table.loading = false
          })
        } else {
          this.table.loading = false
          this.table.data = []
          this.$Notice.error({
            title: '列表加载失败',
            desc: '申请表列表加载失败！' + res.info + '请重试！'
          })
        }
      } catch (error) {
        this.table.loading = false
        this.table.data = []
        this.$Notice.error({
          title: '列表加载失败',
          desc: '申请表列表加载失败！请重试！'
        })
        console.log(error)
      }
    },
    // 在多选模式下有效，只要选中项发生变化时就会触发
    onSelectionChange (selection) {
      this.table.selection = selection
    },
    onChangeSemester (value) {
      if (value) {
        this.filter.studyYear = value.split('/', 2)[0]
        this.filter.semester = value.split('/', 2)[1]
      } else {
        this.filter.studyYear = ''
        this.filter.semester = ''
      }
    },
    // 展开或收起某一行时触发
    onExpand (row, status) {
      this.$nextTick(() => {
        // 展开当前行
        if (status) {
          // 如果当前行已请求过详细信息，则直接展开
          if (row.detail) {
            this.$set(this.table.data[this.table.currRowIndex], '_expanded', true)
            this.$nextTick(() => {
              document.querySelectorAll('#applied-list .ivu-table-cell-expand').forEach(element => {
                element.innerHTML = `<button type="button" style="padding: 1px 7px 2px;" class="ivu-btn ivu-btn-dashed"><span>修改</span></button>`
              })
            })
          } else {
            // 如果当前行未请求过详细信息，先请求再展开
            // this.table.loading = true
            getAppliedFormDetail(row.appCode).then(response => {
              let res = response.data
              if (res.code === 1) {
                // if (res.data.exp_type === 'COURSE') {
                //   res.data.expBaseInfoItems.forEach(item => {
                //     let tempMap = new Map()
                //     item.expTimeItemsCourse.forEach(c => {
                //       if (!tempMap.has(c.index)) {
                //         tempMap.set(c.index, {
                //           sweek: c.expItemTime.sweek,
                //           sdate: c.expItemTime.sdate,
                //           section: new Set().add(c.expItemTime.section),
                //           classroom: new Set().add(JSON.stringify(c.classroom))
                //         })
                //       } else {
                //         tempMap.get(c.index).section.add(c.expItemTime.section)
                //         tempMap.get(c.index).classroom.add(JSON.stringify(c.classroom))
                //       }
                //     })
                //     item.expTimeItemsCourse = Array.from(tempMap)
                //   })
                // }
                this.$set(this.table.data[this.table.currRowIndex], 'formData', res.data)
                this.$set(this.table.data[this.table.currRowIndex], 'detail', true)
                this.$set(this.table.data[this.table.currRowIndex], '_expanded', true)
                this.$nextTick(() => {
                  document.querySelectorAll('#applied-list .ivu-table-cell-expand').forEach(element => {
                    element.innerHTML = `<button type="button" style="padding: 1px 7px 2px;" class="ivu-btn ivu-btn-dashed"><span>修改</span></button>`
                  })
                  this.table.loading = false
                })
              } else {
                this.table.loading = false
                this.$Notice.error({
                  title: '信息加载失败',
                  desc: '申请表详情信息加载失败！' + res.info + '请重试！'
                })
              }
            }).catch(err => {
              this.table.loading = false
              this.$Notice.error({
                title: '信息加载失败',
                desc: '申请表详情信息加载失败！请重试！'
              })
              console.log(err)
            })
          }
        } else {
          // 收起当前行，把当前行数据的_expanded设置为false，避免下次展开其他行时会把该行一并展开
          this.$set(this.table.data[this.table.currRowIndex], '_expanded', false)
          this.$nextTick(() => {
            document.querySelectorAll('#applied-list .ivu-table-cell-expand').forEach(element => {
              element.innerHTML = `<button type="button" style="padding: 1px 7px 2px;" class="ivu-btn ivu-btn-dashed"><span>修改</span></button>`
            })
          })
        }
      })
    },
    // 单击某一行时触发
    onRowClick (row, index) {
      this.table.currRowIndex = index
    },
    // 排序时有效，当点击排序时触发
    onSortChange (column) {
      this.pageBuilderOrder.set(column.key, column.order)
      this.pageBuilderOrderChangeTracker++
    },
    // 添加普通实验申请表
    addApplyForm () {
      this.$router.push({
        name: 'fill_form'
      })
    },
    // 添加实训申请表
    addApplyTraining () {
      this.$router.push({
        name: 'fill_form_training'
      })
    },
    // 批量删除
    batchDelete () {
      if (this.table.selection.length <= 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '请先选择需要批量删除的实验室申请表！'
        })
      } else {
        this.table.selectedRows = this.table.selection
        this.deleteModal.show = true
      }
    },
    // 新增单个实验项目
    addSingle (row) {
      this.modal.saveSingle = {
        show: true,
        exp_type: row.exp_type,
        fieldsetTitle: '实验' + (row.numberOfExperiment + 1) + '基本信息',
        title: '新增实验项目',
        app_code: row.appCode,
        sid: null,
        expIndex: row.numberOfExperiment + 1,
        editSingle: false
      }
    },
    // 修改
    edit (row) {
      this.modal.edit = {
        show: true,
        title: '修改' + (row.exp_type === 'COURSE' ? '普通实验' : '实训') + '申请表',
        expType: row.exp_type,
        appCode: row.appCode
      }
    },
    // 点击导出按钮触发
    exportToExcel (row) {
      this.$set(this.loading.export, row._index, true)
      this.modal.detail.show = true
      this.modal.detail.code = row.appCode
      this.modal.detail.index = row._index
      // 学年
      let title = row.studyYear ? row.studyYear + '~' + (Number(row.studyYear) + 1) + '学年' : ''
      // 学期
      title += row.semester !== '' ? '第' + ['一', '二'][row.semester] + '学期-' : ''
      // 教师名称
      title += row.teacherName ? row.teacherName + '-' : ''
      // 课程名称
      title += row.courseName ? row.courseName + '-' : ''
      title += '实验室申请表'
      this.modal.detail.title = title
    },
    // 导出后回调
    exported (index) {
      this.modal.detail.show = false
      this.$set(this.loading.export, index, false)
    },
    // 修改实验填充表单失败
    failFillBaseFrom (info) {
      this.modal.edit.show = false
      this.$Notice.error({
        title: '获取申请表信息失败，请稍后重试',
        desc: info
      })
    },
    // 修改实验填充表单失败
    failFillExpFrom (info) {
      this.modal.saveSingle.show = false
      this.$Notice.error({
        title: '获取实验项目信息失败，请稍后重试',
        desc: info
      })
    },
    // 删除
    del (row) {
      this.deleteModal.show = true
      this.table.selectedRows = [row]
    },
    // 确认删除
    confirmDel () {
      this.deleteModal.loading = true
      this.deleteModal.closable = false
      this.deleteModal.maskClosable = false
      modifyAppFormStatus(this.table.selectedRows.map(item => {
        return item.appCode
      }), 'DELETED').then(response => {
        let res = response.data
        this.deleteModal.loading = false
        this.deleteModal.show = false
        this.deleteModal.closable = true
        this.deleteModal.maskClosable = true
        if (res.code === 1) {
          this.$Notice.success({
            title: '删除成功',
            desc: '删除所选的实验室申请表成功！'
          })
          // 从当前状态重新加载表格
          this.renderTable(this.filter, this.pageBuilder)
        } else {
          this.$Notice.error({
            title: '删除失败',
            desc: '删除所选的实验室申请表失败！' + res.info + '请重试！'
          })
        }
      }).catch(err => {
        console.log(err)
        this.deleteModal.loading = false
        this.deleteModal.show = false
        this.deleteModal.closable = true
        this.deleteModal.maskClosable = true
        this.$Notice.error({
          title: '删除失败',
          desc: '删除所选的实验室申请表失败！请重试！'
        })
      })
    },
    // 选择
    select (row) {
      this.$emit('selectedPastForm', row.appCode)
    },
    // 选择学院后触发
    onChangeInstitute (value) {
      this.teachers = []
      if (!value) {
        this.filter.institute = ''
        this.filter.teacherCode = ''
        this.table.data = []
      } else {
        this.filter.institute = value
        this.filter.teacherCode = 'all'
      }
      if (this.userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 || this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || this.userAccess.indexOf('ROLE_ROOT') > -1) {
        // 获取某个学院的全部教师
        getTeacherList(this.filter.institute).then(response => {
          let res = response.data
          if (res.code === 1) {
            this.teachers = res.data.length > 0 ? res.data : []
          } else {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取教师列表失败！' + res.info + '请重试！'
            })
          }
        }).catch(err => {
          this.$Notice.error({
            title: '获取列表失败',
            desc: '获取教师列表失败！请重试！'
          })
          console.log(err)
        })
      }
    },
    // 选择教师后触发
    onChangeTeacher (value) {
      this.filter.teacherCode = !value ? '' : value
    },
    // 选择搜索条件后触发
    onChangeSearchCriteria (value) {
      this.search.keyword = ''
      this.filter.teacherName = ''
      this.filter.courseName = ''
      this.search.criteria = value
    },
    // 输入框点击搜索或按下回车键时触发
    onSearch (value) {
      this.filter.teacherName = ''
      this.filter.courseName = ''
      if (this.search.keyword.replace(/(^\s*)|(\s*$)/g, '').length <= 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '搜索的关键字不能为空！'
        })
      } else {
        this.search.keyword = this.search.keyword.replace(/(^\s*)|(\s*$)/g, '')
        this.filter[this.search.criteria] = this.search.keyword
      }
    },
    // 输入框数据改变时触发
    onInputChange (value) {
      this.filter.teacherName = ''
      this.filter.courseName = ''
      if (this.search.keyword.replace(/(^\s*)|(\s*$)/g, '').length <= 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '搜索的关键字不能为空！'
        })
      } else {
        this.search.keyword = this.search.keyword.replace(/(^\s*)|(\s*$)/g, '')
        this.filter[this.search.criteria] = this.search.keyword
      }
    },
    getSortableColumns (columns) {
      let sortableColumns = []
      columns.forEach(item => {
        if (item.sortable) {
          sortableColumns.push(item)
        }
        if (item.children && item.children.length > 0) {
          sortableColumns = sortableColumns.concat(this.getSortableColumns(item.children))
        }
      })
      return sortableColumns
    },
    // 页码改变的回调，返回改变后的页码
    onPageNumChange (value) {
      this.pageBuilder.pageNum = value
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    onPageSizeChange (value) {
      this.pageBuilder.pageNum = 1
      this.pageBuilder.pageSize = value
    },
    // 保存课程信息成功后的回调
    saveBaseSuccess () {
      this.modal.edit.show = false
      // 从当前状态重新加载表格
      this.renderTable(this.filter, this.pageBuilder)
      this.$nextTick(() => {
        this.$Notice.success({
          title: '成功',
          desc: '修改实验室申请表成功。'
        })
      })
    },
    // 保存实验信息成功后的回调
    saveExpSuccess () {
      this.modal.saveSingle.show = false
      // 从当前状态重新加载表格
      this.renderTable(this.filter, this.pageBuilder)
      this.$nextTick(() => {
        this.$Notice.success({
          title: '成功',
          desc: (this.modal.saveSingle.editSingle ? '修改' : '新增') + '实验项目成功。'
        })
      })
    },
    // 关闭 新增 / 修改 申请表的Modal的回调函数
    closeSaveModal () {
      window.location.hash = ''
      this.$nextTick(() => {
        // 全局配置notice组件的属性
        this.$Notice.config({
          top: window.innerHeight / 3
        })
      })
    },
    refreshTable () {
      // 从当前状态重新加载表格
      this.renderTable(this.filter, this.pageBuilder)
    },
    // 动态获取所有的表格列
    getTableColumns (columns) {
      let tableColumns = []
      columns.forEach(item => {
        if (!item.children) {
          tableColumns.push(item)
        }
        if (item.children && item.children.length > 0) {
          tableColumns = tableColumns.concat(this.getTableColumns(item.children))
        }
      })
      return tableColumns
    },
    // 根据key动态获取表格列
    getTableColumnByKey (key) {
      return this.getTableColumns(this.table.columns).filter(item => {
        return item.key === key
      })
    },
    // 修改申请表列表类别筛选条件的回调函数
    onChangeType (value) {
      if (value === 'TRAINING') {
        this.filter.courseType = []
      }
    }
  },
  async created () {
    this.firstEnter = true
    // 全局配置notice组件的属性
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    // 隐藏表格的checkbox列
    if (this.hideCheckBox) {
      this.table.columns.splice(1, 1)
    }
    // 动态设置表格列（类别）的filteredValue初始化的过滤的value集合
    // if (this.formType && this.formType.length > 0) {
    //   this.table.columns.slice(-12, -11)[0].filteredValue = this.formType
    // }
    // 获取课程类别
    // getCourseType().then(response => {
    //   let res = response.data
    //   // *动态设置表格列（课程类别）的filters筛选条件
    //   this.table.columns.slice(-7, -6)[0].filters = res.code === 1 && res.data ? Object.keys(res.data).map(key => {
    //     return {
    //       label: res.data[key],
    //       value: key
    //     }
    //   }) : undefined
    // }).catch(err => {
    //   this.table.columns.slice(-7, -6)[0].filters = undefined
    //   console.log(err)
    // })
    this.table.loading = true
    // 获取课程类别
    this.loading.courseType = true
    getCourseType().then(res => {
      res = res.data
      if (res.code === 1 && res.data) {
        this.options.courseType = Object.keys(res.data).map(key => {
          return {
            label: res.data[key],
            value: key
          }
        })
      } else {
        this.options.courseType = []
        this.$Notice.error({
          title: '获取课程类别失败',
          desc: res.info
        })
      }
      this.loading.courseType = false
    }).catch(error => {
      this.loading.courseType = false
      this.options.courseType = []
      this.$Notice.error({
        title: '获取课程类别失败',
        desc: error
      })
      console.log(error)
    })
    // 获取当前学年和学期
    let filterStudyYear = ''
    let filterSemester = ''
    try {
      let res = await getCurrTermDateInfo()
      if (res.data.code === 1) {
        filterStudyYear = res.data.data.studyYear
        filterSemester = res.data.data.semester
        this.semesterString = res.data.data.studyYear + '/' + res.data.data.semester
      } else {
        this.$Notice.error({
          title: '获取数据失败',
          desc: '获取当前学年、学期失败！' + res.data.info + '请重试！'
        })
      }
    } catch (error) {
      console.log(error)
      this.$Notice.error({
        title: '获取数据失败',
        desc: '获取当前学年、学期失败！请重试！'
      })
    }
    // 获取历史学年和学期列表
    getFirstWeekDateList({
      pageSize: 1000,
      pageNum: 1,
      order: [{
        studyYear: 'desc'
      }, {
        semester: 'desc'
      }]
    }).then(res => {
      if (res.data.code === 1) {
        this.semesters = res.data.data.content.length > 0 ? res.data.data.content.map(item => {
          return item.studyYear + '/' + item.semester
        }) : []
      } else {
        this.$Notice.error({
          title: '列表加载失败',
          desc: '学期列表加载失败！' + res.data.info
        })
      }
    }).catch(error => {
      this.$Notice.error({
        title: '列表加载失败',
        desc: '学期列表加载失败！'
      })
      console.log(error)
    })
    // 获取用户信息
    this.getUserInfo().then(response => {
      let res = response.data
      if (res.code === 1) {
        res = res.data
        // this.filter.institute = res.department || ''
        this.userAccess = res.roles || []
        if (this.userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 || this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || this.userAccess.indexOf('ROLE_ROOT') > -1) {
          this.$nextTick(() => {
            this.$emit('resize-table-height', 47)
          })
        }
        // this.filter.teacherCode = res.code || ''
        this.filter = Object.assign(this.filter, {
          institute: res.department || '',
          teacherCode: res.code || '',
          studyYear: filterStudyYear,
          semester: filterSemester
        })
        if (this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || this.userAccess.indexOf('ROLE_ROOT') > -1) {
          // 获取所有学院
          getInstituteList().then(response => {
            let res = response.data
            if (res.code === 1) {
              this.institutes = res.data.length > 0 ? res.data : []
            } else {
              this.$Notice.error({
                title: '获取列表失败',
                desc: '获取学院列表失败！' + res.info + '请重试！'
              })
            }
          }).catch(err => {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取学院列表失败！请重试！'
            })
            console.log(err)
          })
        }
        if (this.userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 || this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || this.userAccess.indexOf('ROLE_ROOT') > -1) {
          // 获取某个学院的全部教师
          getTeacherList(this.filter.institute).then(response => {
            let res = response.data
            if (res.code === 1) {
              this.teachers = res.data.length > 0 ? res.data : []
            } else {
              this.$Notice.error({
                title: '获取列表失败',
                desc: '获取教师列表失败！' + res.info + '请重试！'
              })
            }
          }).catch(err => {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取教师列表失败！请重试！'
            })
            console.log(err)
          })
        }
      } else {
        this.table.loading = false
        this.$Notice.error({
          title: '获取信息失败',
          desc: '获取用户信息失败！' + res.info + '请重试！'
        })
      }
    }).catch(err => {
      this.table.loading = false
      this.$Notice.error({
        title: '获取信息失败',
        desc: '获取用户信息失败！请重试！'
      })
      console.log(err)
    })
  },
  mounted () {
    this.$nextTick(() => {
      activeTableMove(document.querySelector('#applied-list .ivu-table-body'))
    })
  },
  activated () {
    if (!this.firstEnter) {
      // 全局配置notice组件的属性
      this.$Notice.config({
        top: window.innerHeight / 3
      })
    }
  },
  deactivated () {
    this.firstEnter = false
    this.$Notice.destroy()
  },
  beforeDestroy () {
    this.$Notice.destroy()
  },
  watch: {
    // formType: {
    //   handler: function (value) {
    //     this.filter.type = value.length <= 0 ? '' : value[0]
    //   },
    //   deep: true,
    //   immediate: true
    // },
    filter: {
      handler: function (value, old) {
        if (value.institute) {
          this.pageBuilder.pageNum === 1 ? this.renderTable(value, this.pageBuilder) : this.pageBuilder.pageNum = 1
        }
      },
      deep: true
    },
    pageBuilder: {
      handler: function (value) {
        this.renderTable(this.filter, value)
      },
      deep: true
    },
    'pageBuilder.order': function (value) {
      // iview table 默认只支持单列排序，
      // 除了调用接口进行远程排序外，
      // 还要动态设置表格列的sortType，
      // 实现样式上的显示
      if (!this.table.sortableColumns || this.table.sortableColumns.length <= 0) {
        this.table.sortableColumns = this.getSortableColumns(this.table.columns)
      }
      value.forEach(v => {
        let column = this.table.sortableColumns.filter(item => {
          return item.key === Object.keys(v)[0]
        })
        if (column && column.length > 0) {
          column[0].sortType = v[column[0].key]
        }
      })
    },
    pageBuilderOrderChangeTracker () {
      let tempArray = []
      this.pageBuilderOrder.forEach((value, key, map) => {
        if (value) {
          let obj = {}
          obj[key] = value
          tempArray = tempArray.concat([obj])
        }
      })
      this.pageBuilder.order = tempArray
    }
  }
}
</script>
<style lang="less" scoped>
</style>
<style lang="less">
  #applied-list {
    .ivu-table {
      &-tbody {
        .ivu-table-cell {
          padding-top: 10px;
          padding-bottom: 10px;
          line-height: 1.5rem;
        }

        .ivu-table-cell-with-expand {
          height: auto;
        }
      }
      .add-single {
        &.ivu-btn {
          color: #fff !important;
          background: #ff8a80 !important;
          border-color: #ff8a80 !important;
        }
      }
    }
  }
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal{
      top: 0;
    }
  }
  .mb-50-modal {
    .ivu-modal {
      margin-bottom: 50px;
    }
  }
</style>
